package vn.vfriends.vbox.rest.reader;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.json.Json;
import javax.json.stream.JsonParser;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import vn.vfriends.vbox.model.Storage;

/**
 *
 * @author tuancn
 */
@Provider
@Consumes(MediaType.APPLICATION_JSON)
public class StorageReader implements MessageBodyReader<Storage> {

    @Override
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return type == Storage.class;
    }

    @Override
    public Storage readFrom(Class<Storage> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
        Storage storage = new Storage();
        JsonParser parser = Json.createParser(entityStream);
        while (parser.hasNext()) {
            switch (parser.next()) {
                case KEY_NAME:
                    String key = parser.getString();
                    parser.next();
                    switch (key) {
                        //  Google Profile
                        case "name":
                            storage.setName(parser.getString());
                            break;
                        case "quotaBytesTotal":
                            storage.setQuotaBytesTotal(parser.getLong());
                            break;
                        case "quotaBytesUsed":
                            storage.setQuotaBytesUsed(parser.getLong());
                            break;
                        //  Dropbox profile
                        case "display_name":
                            storage.setName(parser.getString());
                            break;
                        case "quota":
                            storage.setQuotaBytesTotal(parser.getLong());
                            break;
                        case "normal":
                            storage.setQuotaBytesUsed(parser.getLong());
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
        }
        return storage;
    }
    
}
